package com.pjb.springbootjjwt.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.pjb.springbootjjwt.annotation.BusinessException;
import com.pjb.springbootjjwt.annotation.PassToken;
import com.pjb.springbootjjwt.annotation.UserLoginToken;
import com.pjb.springbootjjwt.entity.ClientidSecretModel;
import com.pjb.springbootjjwt.utils.JwtUtils;
import com.pjb.springbootjjwt.entity.SecurityBto;
import com.pjb.springbootjjwt.entity.User;
import com.pjb.springbootjjwt.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;


/**
 * @author jinbin
 * @date 2018-07-08 20:41
 */
@Component
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    @Autowired
    JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    log.error("无token，请重新登录");
                    throw new RuntimeException("无token，请重新登录");
                }
                // 是否过期
                try {
                    jwtUtils.isTokenExpired(token);
                }catch (BusinessException e){
                    throw new RuntimeException("token已经过期");
                } catch (Exception e) {
                    throw new RuntimeException("token解析失败，请确认token是否填写有误");
                }
                // 获取 token 中的 user id
                String userId;
                SecurityBto securityBto;
                try {
                    List<String> audience = JWT.decode(token).getAudience();
                    securityBto = JSON.parseObject(audience.get(0),SecurityBto.class);
                    userId = securityBto.getUserid();
                } catch (Exception j) {
                    throw new BusinessException("token解析失败，请确认token是否填写有误");
                }
                User user = userService.findUserById(userId);
                if (user == null) {
                    throw new RuntimeException("用户不存在，请重新登录");
                }
//                 验证 token

                    jwtUtils.verify(token);

                // 校验其他参数
                checkSecurityInfo(httpServletRequest,securityBto);
                return true;
            }
        }
        return true;
    }
    public  void checkSecurityInfo(HttpServletRequest servletRequest,SecurityBto securityBto){
        // 校验时间戳、clientid、secretKey
        String clientid = servletRequest.getHeader("clientid");
        String secretKey = servletRequest.getHeader("secretKey");
        String timestamp = servletRequest.getHeader("timestamp");
        if(StringUtils.isEmpty(clientid)||StringUtils.isEmpty(secretKey)||StringUtils.isEmpty(timestamp)){
            log.error("token解析异常，请检查token是否正确");
            throw new RuntimeException("token解析异常，请检查token是否正确");
        }
        if(!clientid.equals(securityBto.getClientid())){
            log.error("token解析异常，请检查token是否正确");
            throw new RuntimeException("token解析异常，请检查token是否正确");
        }
        if(!secretKey.equals(securityBto.getSecretKey())){
            log.error("token解析异常，请检查token是否正确");
            throw new RuntimeException("token解析异常，请检查token是否正确");
        }
        if(!timestamp.equals(securityBto.getTimestamp())){
            log.error("token解析异常，请检查token是否正确");
            throw new RuntimeException("token解析异常，请检查token是否正确");
        }
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
